package com.lzx.shop.api;

import com.lzx.shop.dataobject.OrderDO;
import com.lzx.shop.dataobject.PaymentRecordDO;
import com.lzx.shop.enums.NotifyPlatform;
import com.lzx.shop.enums.OrderStatus;
import com.lzx.shop.enums.PaymentStatus;
import com.lzx.shop.helper.DingDingHelper;
import com.lzx.shop.model.Notify;
import com.lzx.shop.model.Result;
import com.lzx.shop.params.PaymentParam;
import com.lzx.shop.service.OrderService;
import com.lzx.shop.service.PayService;
import com.lzx.shop.service.PaymentRecordService;
import com.lzx.shop.utils.ResultUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName PayApi
 * @Author 刘正星
 * @Date 2021/3/27 下午2:50
 * @Description
 */
@Api(tags = "PaymentApi",description = "支付")
@RestController
@RequestMapping("/payment")
public class PaymentApi {

    public static final String MSG = "s% 下单了 s%";

    @Autowired
    private PayService payService;

    @Autowired
    private DingDingHelper dingDingHelper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentRecordService paymentRecordService;

    @PostMapping("/pay")
    public Result payOrder(@RequestBody PaymentParam paymentParam){

        Result result = new Result();
        result.setSuccess(true);
        if (paymentParam == null){
            result.setMsg("failed");
            result.setSuccess(false);
            return result;
        }
        String orderNumber = paymentParam.getOrderNumber();

        PaymentRecordDO paymentRecordDO = new PaymentRecordDO();
        paymentRecordDO.setAmount(paymentParam.getTotalAmount());
        paymentRecordDO.setOrderNumber(paymentParam.getOrderNumber());
        paymentRecordDO.setUserId(paymentParam.getUserId());
        paymentRecordDO.setChannelType(paymentParam.getPayType().toString());
        paymentRecordDO.setPayStatus(PaymentStatus.SUCCESS.toString());
        paymentRecordDO.setPayType(paymentParam.getPayType().toString());
        paymentRecordService.save(paymentRecordDO);
        OrderDO orderDO = orderService.updateOrderStatus(orderNumber, OrderStatus.TRADE_PAID_SUCCESS);

        Notify notify = new Notify();
        notify.setNotifyPlatform(NotifyPlatform.DINGDING);
        notify.setNotifyType("text");
        notify.setTitle("来新订单啦");

        notify.setText("您有一个新的订单，快去处理呀");

        dingDingHelper.sendNotify(notify);

        paymentParam.getProductItems().forEach(productItem -> {
            Result result1 = orderService.updateProduct(productItem.getProductId(),productItem.getNumber());
        });
        return ResultUtil.success(result);

    }



}
